<template>
  <div class="container">
    <Breadcrumb
      :items="[
        'menu.answerthequestionnaireretrieve.form.title',
        'menu.answerthequestionnaire.anserQuestion',
      ]"
    />
    <a-card>
      <a-modal
        v-model:visible="anwserVisible"
        ok-text="提交"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <template #title> 邀请码 </template>
        <div> 请输入正确的邀请码：</div>
        <a-input v-model="invitationCode"></a-input>
      </a-modal>
      <a-descriptions
        :data="header"
        title="问卷"
        :column="{ xs: 1, md: 3, lg: 4 }"
      >
        <a-descriptions-item
          v-for="item of header"
          :key="item"
          :label="item.label"
        >
          <a-tag>{{ item.value }}</a-tag>
        </a-descriptions-item>
      </a-descriptions>

      <div v-if="choiceVisible == true">
        <div style="margin-top: 10px; margin-bottom: 10px"
          >问题： {{ currentQuestion[point].stem }}</div
        >
        <div>
          <a-radio-group
            v-model="currentValue[0]"
            direction="vertical"
            :options="choiceContent"
            size="large"
          >
          </a-radio-group>
        </div>
      </div>
      <div v-if="multiVisible == true">
        <div style="margin-bottom: 10px">
          问题 ： {{ currentQuestion[point].stem }}
        </div>
        <div>
          <a-checkbox-group
            v-model="currentValue"
            :options="choiceContent"
            direction="vertical"
            size="large"
          />
        </div>
      </div>
      <div v-if="gapVisible == true">
        <div style="margin-bottom: 10px"
          >问题： {{ currentQuestion[point].stem }}</div
        >
        <a-input
          v-model="currentValue[0].label"
          :style="{ width: '320px' }"
          placeholder="请输入你的答案"
          allow-clear
        />
      </div>
      <div style="text-align: center">
        <a-button type="primary" @click="handleNext">{{
          buttonCharacter
        }}</a-button>
      </div>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import useLoading from '@/hooks/loading';
  import {
    submitChannelForm,
    BaseInfoModel,
    ChannelInfoModel,
    UnitChannelModel,
  } from '@/api/form';
  import vuedraggable from 'vuedraggable';
  import { ref, reactive, Ref } from 'vue';

  import {
    Survey,
    Question,
    previewsurvey,
    Choice,
    createQuestion,
    answerSurvey,
  } from '@/api/list';
  import loading from '@/hooks/loading';
  import { Breadcrumb, Message } from '@arco-design/web-vue';
  import pagination from '@arco-design/web-vue/es/pagination';
  import { get } from 'http';
  import router from '@/router';
  import { useSurveyStore } from '@/store';

  import BaseInfo from './components/base-info.vue';
  import ChannelInfo from './components/channel-info.vue';
  import Success from './components/success.vue';
  import ChooseQuestionType from './components/choose-question-type.vue';
  import ChoiceQuestion from './components/choice-question.vue';

  const anwserVisible = ref(true);
  const invitationCode = ref('');
  const buttonCharacter = ref('下一题');
  const header = ref([
    {
      label: '问卷名称',
      value: '',
    },
    {
      label: '问卷描述',
      value: '',
    },
  ]);
  const survey = ref({
    answerLimit: 1,
    description: '',
    endTime: '',
    id: '',
    managedBy: '',
    name: 'a',
    questions: [],
    startTime: new Date(),
    typeId: '',
  });
  const surveyStore = useSurveyStore();

  console.log('--- aaa --');
  console.log(useSurveyStore.$id);
  console.log(useSurveyStore().from);
  console.log('-----');
  // point 是
  const point = ref(0);
  // 提交表单的当前下标
  const finalPoint = ref(0);

  // 绑定单位
  const currentValue = ref([]);
  const gapValue = ref('');
  // 设置当前题型的展示情况
  const choiceVisible = ref(false);
  const multiVisible = ref(false);
  const gapVisible = ref(false);

  // 当前加载到页面中的问题（不对） 是所有
  const currentQuestion = ref([
    {
      id: '',
      stem: '',
      questionType: 1,
      nextId: '',
      choices: [{ id: '', content: '', belongTo: '', goTo: '' }],
    },
  ]);
  const finalForm = ref([]);
  const choiceContent = ref([]);
  const isYulan = () => {
    if (useSurveyStore().from === 1) {
      anwserVisible.value = false;
      init(useSurveyStore.$id);
    }
  };
  const handleOk = async () => {
    const { data } = await previewsurvey(invitationCode.value);
    if (data !== '该问卷不存在') {
      anwserVisible.value = false;
      init(data);
    } else {
      Message.error('邀请码错误！');
      anwserVisible.value = true;
    }
  };
  const jugdeType = (k?: number) => {
    if (k === 0) {
      // 单选题

      choiceVisible.value = true;
      multiVisible.value = false;
      gapVisible.value = false;
      currentValue.value.splice(0, currentValue.value.length);
      choiceContent.value.splice(0, choiceContent.value.length);
      for (
        let i = 0;
        i < currentQuestion.value[point.value].choices.length;
        i += 1
      ) {
        choiceContent.value.push({
          label: '',
          value: { goTo: '', id: '', questionId: '' },
        });

        choiceContent.value[i].value.questionId =
          currentQuestion.value[point.value].id;

        choiceContent.value[i].label =
          currentQuestion.value[point.value].choices[i].content;

        choiceContent.value[i].value.goTo =
          currentQuestion.value[point.value].choices[i].goTo;

        choiceContent.value[i].value.id =
          currentQuestion.value[point.value].choices[i].id;
      }
    } else if (k === 1) {
      choiceVisible.value = false;
      multiVisible.value = true;
      gapVisible.value = false;
      console.log('当前问题是多选题');
      currentValue.value.splice(0, currentValue.value.length);
      choiceContent.value.splice(0, choiceContent.value.length);
      for (
        let i = 0;
        i < currentQuestion.value[point.value].choices.length;
        i += 1
      ) {
        choiceContent.value.push({
          label: '',
          value: { goTo: '', id: '', questionId: '' },
        });

        choiceContent.value[i].value.questionId =
          currentQuestion.value[point.value].id;

        choiceContent.value[i].label =
          currentQuestion.value[point.value].choices[i].content;

        choiceContent.value[i].value.goTo =
          currentQuestion.value[point.value].choices[i].goTo;

        choiceContent.value[i].value.id =
          currentQuestion.value[point.value].choices[i].id;
      }
    } else {
      console.log('填空题');

      choiceVisible.value = false;
      multiVisible.value = false;
      gapVisible.value = true;
      currentValue.value.splice(0, currentValue.value.length);
      choiceContent.value.splice(0, choiceContent.value.length);
      currentValue.value.push({
        label: '',
        value: { goTo: '', id: '', questionId: '' },
      });
      currentValue.value[0].value.questionId =
        currentQuestion.value[point.value].id;

      currentValue.value[0].value.goTo =
        currentQuestion.value[point.value].choices[0].goTo;

      currentValue.value[0].value.id =
        currentQuestion.value[point.value].choices[0].id;
    }
  };

  const init = (data: any) => {
    header.value[0].value = data.name;
    header.value[1].value = data.description;
    currentQuestion.value = data.questions;
    const iflabel = data.questions[0].questionType;
    // 对于单选题
    jugdeType(iflabel);
    // survey.value = data;
    // 预加载，如何等到函数执行完毕 再执行其他内容呢
    // const map: Map<string, Question> = getHash(survey.value);
  };
  // list.value.push(...getNextList(survey.questions[0], map));

  const isLast = (point: number) => {
    let isGoTo = true;
    for (let i = 0; i < currentQuestion.value[point].choices.length; i += 1) {
      if (currentQuestion.value[point].choices[i].goTo !== null) {
        isGoTo = false;
        break;
      }
    }
    if (currentQuestion.value[point].nextId === '' && isGoTo === true) {
      if (useSurveyStore().from === 1) {
        buttonCharacter.value = '预览完毕';
      } else {
        buttonCharacter.value = '提交';
      }
    }
  };
  const submit = async (data) => {
    await answerSurvey(data);
  };
  const handleNext = () => {
    // 先将当前的值赋给finalForm 记录下回答的内容
    finalForm.value.push({
      userId: '',
      surveyId: '',
      questionId: '',
      content: '',
      choices: [],
    });

    if (currentQuestion.value[point.value].questionType !== 2) {
      finalForm.value[finalPoint.value].questionId =
        currentValue.value[0].questionId;
      for (let i = 0; i < currentValue.value.length; i += 1) {
        finalForm.value[finalPoint.value].choices[i] = currentValue.value[i].id;
      }
    } else {
      finalForm.value[finalPoint.value].questionId =
        currentValue.value[0].value.questionId;
      finalForm.value[finalPoint.value].content = currentValue.value[0].label;
    }
    if (buttonCharacter.value === '提交') {
      console.log('执行跳转');
      console.log(finalForm.value);
      submit(finalForm.value);
      return;
    }
    if (buttonCharacter.value === '预览完毕') {
      router.push({
        name: 'SurveySearchTable',
      });
    }

    const nextId = ref(currentQuestion.value[point.value].nextId);
    if (nextId.value === '') {
      // 跳转中，我们首先要找到跳转的题目，紧接着根据跳转题目的类型进行组件绑定，同时更新finalPoint，point（currentQuestion）
      let i = 0;

      for (i; i < currentQuestion.value.length; i += 1) {
        if (currentValue.value[0].goTo === currentQuestion.value[i].id) {
          point.value = i;

          isLast(point.value);
          jugdeType(currentQuestion.value[point.value].questionType);
          break;
        }
      }
    } else {
      let i = 0;
      for (i; i < currentQuestion.value.length; i += 1) {
        if (nextId.value === currentQuestion.value[i].id) {
          point.value = i;
          // 重复代码
          isLast(point.value);
          jugdeType(currentQuestion.value[point.value].questionType);
          break;
        }
      }
    }

    finalPoint.value += 1;
  };
</script>

//
<script lang="ts">
  //   export default {
  //     name: 'Step',
  //   };
  //
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  .wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 64px 0;
    background-color: var(--color-bg-2);

    :deep(.arco-form) {
      .arco-form-item {
        &:last-child {
          margin-top: 20px;
        }
      }
    }
  }

  .steps {
    margin-bottom: 76px;
  }
</style>
